package org.report.util;

import jakarta.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author Administrator
 * @describe 说明
 * @date 2024/5/8 0008 11:58
 */
public class FileUtils extends org.apache.commons.io.FileUtils {
    public static File copyResourceFile(String resourceFilePath, String suffix) {
        InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream(resourceFilePath);
        try {
            File tempFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), suffix);
            copyInputStreamToFile(inputStream, tempFile);
            return tempFile;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (Exception ignored) {}
        }
    }

    public static void download(HttpServletResponse response, String filePath, String realFileName) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
             BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            realFileName = URLEncoder.encode(realFileName, StandardCharsets.UTF_8);
            StringBuilder builder = new StringBuilder();
            builder.append("attachment; filename=").append(realFileName).append(";");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
            response.setHeader("Content-disposition", builder.toString());
            response.setHeader("download-filename", realFileName);
            byte[] buff = new byte[2048];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
